import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class GuessNumber extends JFrame implements ActionListener {
    JButton btn_ok,btn_cancel,btn_jx;
    JLabel message,time;
    JTextField user;
    int TYPE = 7;
    int random = new Random().nextInt(99) + 1;

    public GuessNumber() {
        super("GuessNumber");
        JPanel pan = new JPanel();
        Container con = getContentPane();
        Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
        int width = (int) scr.getWidth();
        int height = (int) scr.getHeight();
        btn_ok = new JButton("确认");btn_cancel = new JButton("退出");btn_jx = new JButton("继续"); user = new JTextField(25);
        message = new JLabel("请输入一个1-100之间的整数:");
        time = new JLabel("剩余次数:" + TYPE);
        time.setSize(25,10);
        pan.add(message);pan.add(user); pan.add(time); pan.add(btn_ok); pan.add(btn_jx);pan.add(btn_cancel);
        setLocation((width - 300) / 2, (height - 150) / 2);
        btn_ok.addActionListener(this);btn_cancel.addActionListener(this);btn_jx.addActionListener(this);
        con.add(pan);
        btn_jx.setEnabled(false);
        setResizable(false);
        setSize(300, 145);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if (arg0.getSource() == btn_ok) {
            int r = Integer.parseInt(user.getText().toString().trim());
            if (r >= 100 || r <= 0) {
                message.setText("您输入的数字不正确");
            } else {
                TYPE--;

                if (TYPE <= 0) {
                    time.setText("剩余次数:0" );
                    user.setText(null);
                    message.setText("您没有猜对,游戏结束");
                    btn_jx.setEnabled(true);
                } else {
                    time.setText("剩余次数:" + TYPE);
                    user.setText(null);
                    if (r == random) {
                        message.setText("您猜对了,游戏结束");
                        btn_jx.setEnabled(true);
                    }
                    if (r > random) {
                        message.setText("您输入的数字是:" + r + "错误原因：大了");
                    }else if (r < random) {
                        message.setText("您输入的数字是:" + r + "错误原因：小了");
                    }
                }
            }

        }
        if (arg0.getSource() == btn_jx){

            new GuessNumber();

        }
        if (arg0.getSource() == btn_cancel) {
            setVisible(false);
            dispose();
            System.exit(0);
        }
    }

    public static void main(String[] args) {
        new GuessNumber();
    }
}
